﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using System.Collections;
using DispatchAssist.Service;
using System.Web.Services.Protocols;
using DispatchAssist.BusinessLogical.Model;

namespace DispatchAssist.AppHost
{
    [ModuleContract("59D7C60D-7DAB-E011-9462-00505689007F", "系统管理", "警告规则管理")]
    public partial class AlertRuleManage : MdiUserControl
    {
        RuleManagerService service = new RuleManagerService();
        List<DispatchAssist.Service.AlertRule> alertRuleLst = null;

        int previewIndex = 0;

        public AlertRuleManage()
            : base()
        {
            InitializeComponent();
        }
        public AlertRuleManage(XmlNode xn)
            : this()
        {
        }

        private void BindAlertActionDefines()
        {
            try
            {
                List<DispatchAssist.Service.AlertActionDefine> checks = service.GetAllAlertActionDefineRecords().ToList<DispatchAssist.Service.AlertActionDefine>();
                this.chklistAlertAction.DataSource = checks;
                this.chklistAlertAction.DisplayMember = "AlertActionName";
                this.chklistAlertAction.ValueMember = "AlertActionFlag";
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void BindDataGrid()
        {
            try
            {
                alertRuleLst = service.GetAllAlertRuleRecords().ToList<DispatchAssist.Service.AlertRule>();
                dgAlertRuleList.Rows.Clear(); ;
                int i = 0;
                foreach (DispatchAssist.Service.AlertRule au in alertRuleLst)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    dgAlertRuleList.Rows.Add(row);
                    dgAlertRuleList.Rows[i].Cells[0].Value = au.AlertRuleID;
                    if (au.Airport == "0000") dgAlertRuleList.Rows[i].Cells[1].Value = "通用规则机场";
                    else dgAlertRuleList.Rows[i].Cells[1].Value = au.Airport;
                    dgAlertRuleList.Rows[i].Cells[2].Value = getWarnLevelName(au.WarnLevel);
                    dgAlertRuleList.Rows[i].Cells[3].Value = getAlertActionFalgStr(au.AlertActionFlag);
                    i++;
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private string getWarnLevelName(int warnLevel)
        {
            string str = "";
            switch (warnLevel)
            {
                case 1:
                    str = "红色";
                    break;
                case 2:
                    str = "黄色";
                    break;
                case 3:
                    str = "蓝色";
                    break;
                default:
                    str = "无";
                    break;
            }

            return str;
        }

        private string getAlertActionFalgStr(int alertActionFlag)
        {
            string str = "";
            ArrayList al = GetCheckedItemsByAlertActionFlag(alertActionFlag);

            List<DispatchAssist.Service.AlertActionDefine> checks = service.GetAllAlertActionDefineRecords().ToList<DispatchAssist.Service.AlertActionDefine>();
            foreach (int alertaction in al)
            {
                DispatchAssist.Service.AlertActionDefine aad = checks.Find(s => s.AlertActionFlag == alertaction);
                str += aad.AlertActionName + "  |  ";
            }
            str = str.Substring(0, str.Length - 5);
            return str;
        }

        private void setControlsEnabled(bool boo)
        {
            //txtAirPortCode.Enabled = boo;
            chklistAlertAction.Enabled = boo;
            cmbWarnLevel.Enabled = boo;
            btnSave.Enabled = boo;
            btnCancel.Enabled = boo;

            //dgAlertRuleList.Enabled = !boo;

        }

        private void setBtnEnabled(bool boo)
        {
            btnDelete.Enabled = boo;
            btnCreate.Enabled = boo;
            btnEdit.Enabled = boo;
        }

        private void setControlsEmpty()
        {
            txtAirPortCode.Text = "";
            txtAirPortCode.Focus();

            if (chklistAlertAction.Items.Count > 0)
            {
                for (int i = 0; i < chklistAlertAction.Items.Count; i++)
                {
                    chklistAlertAction.SetItemChecked(i, false);
                }
            }
            cmbWarnLevel.SelectedIndex = 0; ;
        }

        public override void Onload()
        {
            service.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            dgAlertRuleList.MultiSelect = false;
            BindAlertActionDefines();
            grpAlertRuleInfo.Visible = false;
            BindDataGrid();
            //cmbWarnLevel.SelectedIndex = 0;
            setControlsEnabled(false);
            base.Onload();
        }

        private ArrayList GetCheckedItemsByAlertActionFlag(int AlertActionFlag)
        {

            ArrayList al = new ArrayList();
            List<DispatchAssist.Service.AlertActionDefine> checks = service.GetAllAlertActionDefineRecords().ToList<DispatchAssist.Service.AlertActionDefine>();

            foreach (DispatchAssist.Service.AlertActionDefine alertActionDefine in checks)
            {
                if ((AlertActionFlag & alertActionDefine.AlertActionFlag) == alertActionDefine.AlertActionFlag) al.Add(alertActionDefine.AlertActionFlag);
            }
            return al;
        }

        private void SetCheckedItems(ArrayList checkedArr)
        {

            if (chklistAlertAction.Items.Count > 0)
            {
                for (int i = 0; i < chklistAlertAction.Items.Count; i++)
                {
                    chklistAlertAction.SetItemChecked(i, false);
                }

                for (int i = 0; i < chklistAlertAction.Items.Count; i++)
                {
                    if (checkedArr.Contains(((DispatchAssist.Service.AlertActionDefine)chklistAlertAction.Items[i]).AlertActionFlag))
                    {
                        chklistAlertAction.SetItemChecked(i, true);
                    }
                }
            }
        }

        #region EventHandlers

        private void dgAlertRuleList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgAlertRuleList.Rows.Count == 0) return;

            int index = dgAlertRuleList.CurrentRow.Index;
            DispatchAssist.Service.AlertRule alertRule = new DispatchAssist.Service.AlertRule();
            bool flag = false;
            if (dgAlertRuleList.Rows[index].Cells[0].Value == null)
            {
                if (alertRuleLst.Count > 0)
                {
                    if (index > alertRuleLst.Count - 1)
                    {
                        alertRule = new DispatchAssist.Service.AlertRule(); setBtnEnabled(false);
                    }
                    else
                    {
                        alertRule = alertRuleLst[0];
                        setBtnEnabled(true);
                    }
                }
                else
                {
                    setBtnEnabled(true);
                    return;
                }
            }
            else
            {
                Guid selectedID;
                if ((grpAlertRuleInfo.Visible == true))
                {
                    if (MessageBox.Show("是否确定撤销当前编辑？", "确认框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        grpAlertRuleInfo.Visible = false;
                        btnCancel.Tag = "none";

                        selectedID = (Guid)dgAlertRuleList.Rows[index].Cells[0].Value;
                        dgAlertRuleList.Rows[index].Selected = true;

                        setBtnEnabled(true);
                    }
                    else
                    {

                        grpAlertRuleInfo.Visible = false;
                        selectedID = (Guid)dgAlertRuleList.Rows[previewIndex].Cells[0].Value;
                        dgAlertRuleList.Rows[previewIndex].Selected = true;
                        dgAlertRuleList.CurrentCell = dgAlertRuleList.Rows[previewIndex].Cells[1];
                        dgAlertRuleList.ClearSelection();

                        grpAlertRuleInfo.Visible = true;

                        setBtnEnabled(false);

                        if (btnSave.Tag.ToString() == "create")
                        {
                            flag = true;
                            btnCreate_Click(null, null);
                            //txtAirPortCode.Enabled = true;
                        }


                    }

                }
                else
                {
                    selectedID = (Guid)dgAlertRuleList.Rows[index].Cells[0].Value;
                    dgAlertRuleList.Rows[index].Selected = true;
                    setBtnEnabled(true);
                }

                alertRule = alertRuleLst.Find(s => s.AlertRuleID == selectedID);
                if (alertRule == null) alertRule = new DispatchAssist.Service.AlertRule();

                //if (!flag)
                {
                    if (alertRule.Airport == "0000") { btnDelete.Enabled = false; btnCreate.Enabled = true; btnEdit.Enabled = true; txtAirPortCode.Enabled = false; } else { setControlsEnabled(true); txtAirPortCode.Enabled = true; }
                }

            }

            if (!flag)
            {
                txtAirPortCode.Text = (alertRule.Airport == "0000") ? "通用规则机场" : alertRule.Airport;
                cmbWarnLevel.SelectedIndex = alertRule.WarnLevel;

                ArrayList al = GetCheckedItemsByAlertActionFlag(alertRule.AlertActionFlag);
                SetCheckedItems(al);
                //chklistAlertAction.
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string tagstr = (sender as Button).Tag.ToString();
                List<DispatchAssist.Service.AlertRule> lst = service.GetAllAlertRuleRecords().ToList<DispatchAssist.Service.AlertRule>();

                DispatchAssist.Service.AlertRule ar = lst.Find(s => s.Airport == (txtAirPortCode.Text == "通用规则机场" ? "0000" : txtAirPortCode.Text) && s.WarnLevel == cmbWarnLevel.SelectedIndex);

                List<DispatchAssist.Service.InfoAirport> lstAirports = service.GetAllAirports().ToList<DispatchAssist.Service.InfoAirport>();

                DispatchAssist.Service.InfoAirport airport = lstAirports.Find(s => s.Code3 == txtAirPortCode.Text);

                if (string.IsNullOrEmpty(txtAirPortCode.Text))
                {
                    MessageBox.Show("请输入机场编码！");
                    return;
                }

                if (airport == null && txtAirPortCode.Text != "通用规则机场")
                {
                    MessageBox.Show("输入的机场编码不正确！");
                    txtAirPortCode.Focus();
                    return;
                }

                if (cmbWarnLevel.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择警告级别！");
                    return;
                }
                if (chklistAlertAction.CheckedItems.Count == 0)
                {
                    MessageBox.Show("请选择警告方式！");
                    return;
                }

                // add at 2011-8-18 by wuzhongqi
                string valMessage = SelectedRule();

                if (!string.IsNullOrEmpty(valMessage))
                {
                    MessageBox.Show(valMessage);
                    return;
                }


                DispatchAssist.Service.AlertRule alertRule = null;
                if (tagstr == "create")
                {
                    if (ar != null)
                    {
                        MessageBox.Show("警告规则已经存在！");
                        return;
                    }
                    alertRule = new DispatchAssist.Service.AlertRule();

                }
                else if (tagstr == "alter")
                {
                    alertRule = lst.Find(s => s.AlertRuleID == ((Guid)(dgAlertRuleList.CurrentRow.Cells[0].Value)));
                    if ((alertRule.Airport != ((txtAirPortCode.Text == "通用规则机场") ? "0000" : txtAirPortCode.Text) || alertRule.WarnLevel != cmbWarnLevel.SelectedIndex) && ar != null)
                    {
                        MessageBox.Show("警告规则已经存在！");
                        return;
                    }
                }

                alertRule.Airport = (txtAirPortCode.Text == "通用规则机场") ? "0000" : txtAirPortCode.Text;

                alertRule.WarnLevel = (int)(cmbWarnLevel.SelectedIndex);

                int actionFlag = 0;
                if (chklistAlertAction.Items.Count > 0)
                {
                    for (int i = 0; i <= chklistAlertAction.Items.Count - 1; i++)
                    {
                        if (chklistAlertAction.GetItemChecked(i))
                        {
                            int alertActionFlag = ((DispatchAssist.Service.AlertActionDefine)(chklistAlertAction.Items[i])).AlertActionFlag;
                            actionFlag = actionFlag | alertActionFlag;
                        }
                    }
                }
                alertRule.AlertActionFlag = actionFlag;

                alertRule.LastModifyTime = DateTime.Now;

                if (tagstr == "create")
                {
                    if (service.CreateAlertRule(alertRule))
                    {
                        MessageBox.Show("添加成功！");
                        grpAlertRuleInfo.Visible = false;
                        BindDataGrid();
                        dgAlertRuleList.Rows[0].Selected = true;
                        dgAlertRuleList.CurrentCell = dgAlertRuleList.Rows[0].Cells[1];
                        dgAlertRuleList_SelectionChanged(null, null);

                        setControlsEnabled(false);
                        //btnEdit.Enabled = true;
                        ////btnDelete.Enabled = true;
                        //btnCreate.Enabled = true;

                    }
                    else
                    {
                        MessageBox.Show("保存失败！");
                    }

                }
                else if (tagstr == "alter")
                {
                    if (service.UpdateAlertRule(alertRule))
                    {
                        MessageBox.Show("修改成功！");
                        grpAlertRuleInfo.Visible = false;
                        int indexx = dgAlertRuleList.CurrentRow.Index;
                        BindDataGrid();
                        dgAlertRuleList.Rows[indexx].Selected = true;
                        dgAlertRuleList.CurrentCell = dgAlertRuleList.Rows[indexx].Cells[1];
                        dgAlertRuleList_SelectionChanged(null, null);
                        setControlsEnabled(false);

                        //btnEdit.Enabled = true;
                        //btnDelete.Enabled = true;
                        //btnCreate.Enabled = true;


                    }
                    else
                    {
                        MessageBox.Show("保存失败！");
                    }
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);

            }
            catch (Exception ex)
            {

                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            btnSave.Tag = "create";
            setControlsEnabled(true);
            setControlsEmpty();
            grpAlertRuleInfo.Visible = true;

            txtAirPortCode.Enabled = true;
            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            btnCreate.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            btnSave.Tag = "alter";
            //btnCancel.Tag = "mess";
            setControlsEnabled(true);
            grpAlertRuleInfo.Visible = true;
            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            btnCreate.Enabled = false;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgAlertRuleList.CurrentRow.Index < 0 || dgAlertRuleList.CurrentRow.Index > alertRuleLst.Count - 1)
            {
                MessageBox.Show("请选择一条警告规则！");
                return;
            }
            if (MessageBox.Show("确认删除此记录？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }

            Guid alertRuleID = new Guid((dgAlertRuleList.CurrentRow.Cells["AlertRuleID"].Value).ToString());


            try
            {
                if (service.DeleteAlertRule(alertRuleID))
                {
                    MessageBox.Show("删除成功");
                    BindDataGrid();
                    dgAlertRuleList.Rows[0].Selected = true;
                    dgAlertRuleList.CurrentCell = dgAlertRuleList.Rows[0].Cells[1];
                    dgAlertRuleList_SelectionChanged(null, null);
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);

            }
            catch (Exception ex)
            {

                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            grpAlertRuleInfo.Visible = false;
            if (btnSave.Tag.ToString() == "create")
            {
                dgAlertRuleList.Rows[0].Selected = true;
                dgAlertRuleList.CurrentCell = dgAlertRuleList.Rows[0].Cells[1];
            }
            else if (btnSave.Tag.ToString() == "alter")
            {
                //dgAlertRuleList.Rows[dgAlertRuleList.CurrentRow.Index].Selected = true;

            }

            dgAlertRuleList_SelectionChanged(null, null);
            setControlsEnabled(false);



        }

        private void dgAlertRuleList_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            previewIndex = e.RowIndex;
        }

        private void chklistAlertAction_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private string SelectedRule()
        {

            string result = "";

            int selectedActionSum = chklistAlertAction.CheckedItems.Cast<DispatchAssist.Service.AlertActionDefine>().ToDictionary<DispatchAssist.Service.AlertActionDefine, int>(f => f.AlertActionFlag).Keys.Sum();

            if ((selectedActionSum | (int)Enums.AlertActionFlag.ManualSendAcrarsAlert) == selectedActionSum && (selectedActionSum | (int)(Enums.AlertActionFlag.AutoSendAcarsAlert | Enums.AlertActionFlag.ConfirmAcars)) == selectedActionSum)
            {
                result = "不能同时选中手动发送Acars和自动发送Acars预警模式";
            }
            if ((selectedActionSum | (int)Enums.AlertActionFlag.ManualSendSMSAlert) == selectedActionSum && (selectedActionSum | (int)(Enums.AlertActionFlag.AutoSendSMSAlert | Enums.AlertActionFlag.ConfirmSMS)) == selectedActionSum)
            {
                result = "   不能同时选中手动发送短信和自动发送短信预警模式";
            }

            return result;
        }


        #endregion
    }
}
